package com.digital.herbarium.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.digital.herbarium.Entity.Role;
import com.digital.herbarium.Entity.RoleMenu;
import com.digital.herbarium.Exception.CustomException;
import com.digital.herbarium.Mapper.RoleMapper;
import com.digital.herbarium.Util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleService {

    @Autowired
    RoleMapper roleMapper;
    @Autowired
    MenuService menuService;

   public List<Role> getRoleInfo(Role role){
        return roleMapper.getRoleInfo(role);
    }

    public void addRole(Role role){

        check(role);
        role.setState(1);
        role.setCreatetime(TimeUtil.getNow());
        roleMapper.addRole(role);
        addRoleMenu(role);


    }

    public void addRoleMenu(Role role){
        //添加关联关系
        if(!StrUtil.hasEmpty(role.getMenuid()) && !StrUtil.hasBlank(role.getMenuid())){
            List<RoleMenu> rm = new ArrayList<>();
            String[] strArr = role.getMenuid().split(",");
            for (int i = 0; i < strArr.length; i++) {
                RoleMenu r = new RoleMenu();
                r.setRoleid(role.getId());
                r.setMenuid(Integer.valueOf(strArr[i]));
                rm.add(r);

            }
            roleMapper.bachAdd(rm);
        }
    }
    public  void editRole(Role role){
       if(role.getId() == null || role.getId() == 0){
           throw new CustomException(400,"参数非法");
       }
        //先删除关联关系
        String[] strArr = role.getId().toString().split(",");
        Long[] ids = Convert.toLongArray(strArr);
        roleMapper.delRoleMenu(ids);
        check(role);
        roleMapper.editRole(role);
        addRoleMenu(role);

    }

    public  void check(Role role){
        if(StrUtil.hasEmpty(role.getRolecode()) || StrUtil.hasBlank(role.getRolecode())){
            throw new CustomException(400,"角色编码不能为空");
        }
        if(StrUtil.hasEmpty(role.getRolename()) || StrUtil.hasBlank(role.getRolename())){
            throw new CustomException(400,"角色名称不能为空");
        }
        Integer codes = roleMapper.getCount(role);
        if(codes > 0){
            throw new CustomException(400,"该角色已存在");
        }
    }

    public void delRole(String id){
        if(StrUtil.hasEmpty(id) || StrUtil.hasBlank(id)){
            throw  new CustomException(400,"缺少信息id");
        }
        String[] strArr = id.split(",");
        Long[] ids = Convert.toLongArray(strArr);
        roleMapper.delRole(ids);
        //删除关联表
        roleMapper.delRoleMenu(ids);

    }


}
